/*
 * @Author: taiyunhang
 * @Date: 2019-01-14 10:12:54
 * */

<template>
  <div class="v-container">
    <v-header title="网点查询">
      <span class="back" @click="goBack">
        <i class="el-icon-arrow-left"></i>返回
      </span>
      <div class="switch"><img @click="switchView" :src="switchImg" width="30"></div>
    </v-header>
    <div class="v-main">
      <div class="alllist">
        <div class="drop-title" @click="showAreaList">
          <span class="drop-text">{{areaName}}</span>
          <i class="el-icon-arrow-down drop-icon" :class="{'active':isDropActive}"></i>
        </div>
        <ul class="drop-list" v-show="isDropActive">
          <li v-for="item in areaList" :key="item.id" @click="resetPoint(item.name, item.lnglat,item.areaId)" :class="{'activeArea':item.areaId === currentAreaId}">{{item.name}}</li>
          <li @click="resetPoint('全部',$store.state.cityName,'')" :class="{'activeArea':'' === currentAreaId}">全部</li>
        </ul>
      </div>
      <div class="point-wrapper">
        <div class="bmap-wrapper" v-show="!isList">
          <baidu-map ref="bmap" class="bm-view" :center="mapCenter" :zoom="mapZoom" :scroll-wheel-zoom="true">
            <bm-circle :center="circlePath.center" :radius="circlePath.radius" stroke-color="blue" :stroke-opacity="0.5" :stroke-weight="2" @lineupdate="updateCirclePath" :editing="false"></bm-circle>
            <bm-marker v-for="item in webList" :key="item.id" :position="{lng:item.lnglat.lng, lat:item.lnglat.lat}" :offset="{width:0,height:-20}" :icon="{url: mapIcon1, size: {width: 26, height: 41}}" :zIndex="1" @click="openShopInfo($event,item)"></bm-marker>
          </baidu-map>
          <div class="address" v-show="showShopInfo">
            <div class="sh-logo">
              <img src="@/assets/images/icon_sh.png" width="28" height="40">
            </div>
            <div class="sh-logo" @click="selectNavigate(activeShop.lnglat)">
              <img src="@/assets/images/icon_dh.png" width="28" height="40">
            </div>
            <h4 class="net-name">{{activeShop.shopName}}<i class="offline-text" v-if="activeShop.status === 3">——下线中</i></h4>
            <p class="net-address">{{activeShop.address}}({{activeShop.shopDistance}})</p>
            <div class="net-telphone">联系电话：<a :href="`tel:${activeShop.telephone}`">{{activeShop.telephone}}</a></div>
          </div>
        </div>
        <div class="page-loadmore-wrapper" ref="wrapper" v-show="isList" :style="{ height: wrapperHeight + 'px' }">
          <mt-loadmore :bottom-method="loadBottom" @bottom-status-change="handleBottomChange" :bottom-all-loaded="allLoaded" ref="loadmore">
            <ul>
              <li class="point-list" v-for="item in webList" :key="item.id">
                <div class="point-item" :class="{'offline':item.status === 3}">
                  <span class="l-logo"><img v-lazy="item.logoPath" class="page-lazyload-image" width="92"></span>
                  <div class="pdetail">
                    <h4>{{item.shopName}}</h4>
                    <p class="l-address">{{item.address}}</p>
                    <div class="l-other"><img src="@/assets/images/iocn3_time.png" width="12" alt="营业时间">{{item.shopTime}}</div>
                    <div class="l-other"><img src="@/assets/images/iocn3_loc.png" width="12" alt="距离">{{item.shopDistance}}</div>
                    <div class="l-other"><img src="@/assets/images/iocn3_phone.png" width="12" alt="电话">{{item.telephone}}</div>
                    <div class="l-navi" @click="selectNavigate(item.lnglat)"><img src="@/assets/images/icon_dh2.png" width="46" alt="导航"></div>
                  </div>
                </div>
              </li>
            </ul>
            <div slot="bottom" class="mint-loadmore-bottom">
              <span v-show="bottomStatus !== 'loading'" :class="{ 'is-rotate': bottomStatus === 'drop' }">↑</span>
              <span v-show="bottomStatus === 'loading'">
                <mt-spinner type="snake"></mt-spinner>
              </span>
            </div>
          </mt-loadmore>
        </div>
      </div>
    </div>
    <mt-actionsheet :actions="naviActions" v-model="naviVisible"></mt-actionsheet>
  </div>
</template>

<script>
import vHeader from '@/components/Header.vue';
import { Resource } from '@/services/resource';
import { BaiduMap } from '@/components/bmap-components';
import bmapapi from '@/common/utils/bmap/bmapapi';
import axios from 'axios';

const listImg = require('@/assets/images/list.png');
const mapImg = require('@/assets/images/map.png');
const myIcon = require('@/assets/images/my_icon.png');
const mapIcon1 = require('@/assets/images/map_icon1.png');
const mapIcon2 = require('@/assets/images/map_icon2.png');

export default {
  name: 'point',
  components: {
    vHeader,
    BaiduMap
  },
  data() {
    return {
      showShopInfo: false,
      myIcon,
      mapIcon1,
      mapIcon2,
      mapCenter: this.$store.state.cityName,
      mapZoom: 14,
      switchImg: mapImg,
      isDropActive: false,
      isList: true,
      areaList: [],
      webList: [],
      circlePath: {
        center: {
          lng: 116.404,
          lat: 39.915
        },
        radius: 500
      },
      pageNo: 1,
      areaName: '全部',
      naviVisible: false,
      naviActions: [
        { name: '高德地图', method: () => this.navigate('gd') },
        { name: '腾讯地图', method: () => this.navigate('tx') },
        { name: '百度地图', method: () => this.navigate('bd') }
      ],
      qq: window.qq,
      wrapperHeight: 0,
      allLoaded: false,
      bottomStatus: '',
      activeMarker: null,
      activeShop: {},
      currentAreaId: ''
    };
  },
  beforeCreate() {
    this.$store.dispatch('setCityName', '重庆市');
  },
  mounted() {
    sessionStorage.areaId = '';
    this.wrapperHeight = document.documentElement.clientHeight - this.$refs.wrapper.getBoundingClientRect().top;
    this.getAreaList();
  },
  computed: {},
  methods: {
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    },
    // 获取城市区域
    getAreaList() {
      Resource.getAreaList.post({}, { cityName: this.$store.state.cityName }, {}).then(res => {
        let data = res.areaList;
        data.map(item => {
          let _mapArr = item.coordinate.split(',');
          item.lnglat = { lng: _mapArr[0], lat: _mapArr[1] };
          return item;
        });
        console.log(data);
        this.areaList = data;
      });
    },
    // 获取网点列表
    getWebList(pageNo) {
      return Resource.getWebList
        .post(
          {},
          {
            cityName: this.$store.state.cityName,
            longitude: sessionStorage.longitude,
            latitude: sessionStorage.latitude,
            areaId: sessionStorage.areaId,
            pageNo,
            pageSize: 10
          },
          {}
        )
        .then(res => {
          let data = res.shopList;
          data = eval('(' + data + ')');
          if (data) {
            console.log(data);
            data.map(item => {
              let { openTime, restTime } = item;
              if (!openTime) {
                openTime = '8:00';
              } else {
                openTime = openTime.replace(/^\s*|\s*$/g, '');
              }
              if (!restTime) {
                restTime = '20:00';
              } else {
                restTime = restTime.replace(/^\s*|\s*$/g, '');
              }
              item.shopTime = openTime + '-' + restTime;
              let _mapArr = item.coordinate.split(',');
              item.lnglat = { lng: _mapArr[0], lat: _mapArr[1] };
              return item;
            });
          }
          return data || [];
        });
    },
    // 切换地图、列表两种视图模式
    switchView() {
      this.isList = !this.isList;
      this.switchImg = this.isList ? mapImg : listImg;
    },
    // 初始化网点列表及地图
    initialPoint() {
      this.getWebList(1).then(res => {
        console.log(res);
        this.webList = res;
      });
    },
    // 重置网点列表及地图
    resetPoint(areaName, lnglat, areaId) {
      let { map, BMap } = this.$refs.bmap;
      let { lng, lat } = lnglat;
      map.setZoom(14);
      if (areaName === '全部') {
        map.setCenter(lnglat);
      } else {
        map.panTo(new BMap.Point(lng, lat)); // 改变地图中心点
      }
      if (this.activeMarker) {
        let c1Icon = bmapapi.icon(this.mapIcon1, bmapapi.size(26, 41));
        this.activeMarker.setIcon(c1Icon);
      }
      this.showShopInfo = false;
      this.areaName = areaName;
      this.isDropActive = false;
      this.currentAreaId = sessionStorage.areaId = areaId;
      this.allLoaded = false;
      this.initialPoint();
    },
    // 点击展示区域列表
    showAreaList() {
      this.isDropActive = !this.isDropActive;
    },
    // 选择导航方式
    selectNavigate(lnglat) {
      let { lng, lat } = lnglat;
      sessionStorage.navLng = lng;
      sessionStorage.navLat = lat;
      this.naviVisible = true;
    },
    // 百度、高德、腾讯导航
    navigate(style) {
      if (style == 'bd') {
        window.location.href = `https://api.map.baidu.com/direction?origin=latlng:${sessionStorage.latitude},${
          sessionStorage.longitude
        }|name:我的位置&destination=latlng:${sessionStorage.navLat},${sessionStorage.navLng}|name:我的终点&mode=driving&origin_region=${
          sessionStorage.gps
        }&destination_region=长沙市&output=html&coord_type=bd09ll&src=myAppName`;
      } else if (style == 'gd') {
        // 转换百度坐标为高德坐标 调高德导航
        axios
          .get(
            `https://restapi.amap.com/v3/assistant/coordinate/convert?key=17d277e5a61eda694c1784737631c319&locations=${
              sessionStorage.longitude
            },${sessionStorage.latitude}|${sessionStorage.navLng},${sessionStorage.navLat}&coordsys=baidu`
          )
          .then(res => {
            if (res.status == 1) {
              var locations = res.locations.split(';');
              let startPt = locations[0].split(',');
              startPt.lng = startPt[0];
              startPt.lat = startPt[1];
              let endPt = locations[1].split(',');
              endPt.lng = endPt[0];
              endPt.lat = endPt[1];
              window.location.href = `https://uri.amap.com/navigation?from=&to=${endPt.lng},${
                endPt.lat
              },我的终点&mode=car&policy=0&coordinate=gaode&callnative=1`;
            }
          });
      } else if (style == 'tx') {
        // 转换百度坐标为腾讯坐标
        this.qq.maps.convertor.translate(new this.qq.maps.LatLng(sessionStorage.navLat, sessionStorage.navLng), 3, function(res) {
          let latlng = res[0];
          window.location.href = `https://apis.map.qq.com/uri/v1/routeplan?type=drive&to=中关村&tocoord=${latlng.lat},${
            latlng.lng
          }&policy=1&referer=myapp`;
        });
      }
    },
    // 地图中点击某个网点
    openShopInfo(event, item) {
      console.log(event);
      this.activeShop = item;
      this.showShopInfo = true;
      if (this.activeMarker) {
        let c1Icon = bmapapi.icon(this.mapIcon1, bmapapi.size(26, 41));
        this.activeMarker.setIcon(c1Icon);
      }
      setTimeout(() => {
        let c2Icon = bmapapi.icon(this.mapIcon2, bmapapi.size(26, 41));
        event.currentTarget.setIcon(c2Icon);
        this.activeMarker = event.currentTarget;
      }, 0);
    },
    // 底部上拉加载更多网点
    loadBottom() {
      this.getWebList(this.pageNo).then(res => {
        this.webList = this.webList.concat(res);
        if (res.length < 10) {
          this.allLoaded = true;
        }
        this.$refs.loadmore.onBottomLoaded();
        console.log(this.webList);
        if (this.pageNo === 1) {
          setTimeout(() => {
            this.$refs.loadmore.scrollEventTarget.scrollTop = 0;
          }, 0);
        }
        this.pageNo++;
      });
    },
    handleBottomChange(status) {
      this.bottomStatus = status;
    },
    updateCirclePath(e) {
      this.circlePath.center = e.target.getCenter();
      this.circlePath.radius = e.target.getRadius();
    }
  }
};
</script>

<style lang="less" scoped>
@import url('./point.less');
</style>
